﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.ServiceModel.Activation;
using Medianamik.UI.Lock;
using NLog;
using System.Xml.Linq;
using System.Collections.Specialized;

namespace Medianamik.UI.Lock
{
    // NOTE: If you change the class name "LockService" here, you must also update the reference to "LockService" in App.config.
    
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class LockService : ILockService
    {

        public int Ping(Guid pObjectId)
        {
            try
            {

                var transac = LockContext.CurrentTransaction;
                if (transac == null) { return (int)LockStatus.Elapsed ; }

              return (int)transac.KeepAlive(pObjectId);
               
            }
            catch (Exception e)
            {
                LogManager.GetLogger("*").ErrorException("Erreur lors du renouvellement du Lock", e);
            }

            //En cas de probleme on veut que les Usagers puissent continuer  a editer
            return (int)LockStatus.KeepAlive;
        }

        public int Lock(Guid pObjectId, int pUltimatum)
        {
            try
            {
                if (LockManager.IsLocked(pObjectId))
                {
                    return (int)LockStatus.Elapsed;
                }

                Transaction t = LockContext.CurrentTransaction;
                if (t == null) { t = new Transaction(); }
                t.Lock(pObjectId, TimeSpan.FromSeconds(pUltimatum), HttpContext.Current.User.Identity.Name );
                
            }
            catch (Exception e)
            {
                LogManager.GetCurrentClassLogger().ErrorException("Erreur lors de la demande de Lock", e);
                throw;
            }
            return (int)LockStatus.KeepAlive;
        }

        public bool Unlock(Guid pObjectId)
        {
            Transaction t = LockContext.CurrentTransaction;
            t.Unlock(pObjectId);
            return true;
        }

        
    
    }
}
